/**
 * 工商变更
 * @author   Liu Yutao <koal@vip.qq.com>
 * @date     2018/3/15 10:24
 */

/**
 * 证件类型隐藏学历、电话、电子邮箱
 * 相应cardType的change事件
 * @param event
 */
function memberCardTypeSwitch(event) {
    var currentForm = $(event.target).parents("form");
    currentForm.find("select[name=cardType]").on('change', function () {
        memberCardTypeSwitchExecute(this, currentForm);
    });
}

/**
 * 证件类型实际执行方法
 */
function memberCardTypeSwitchExecute(thiz, currentForm) {
    if ($(thiz).val() != 1) {
        currentForm.find(".education-box").hide().find("input").attr("disabled", true);
        currentForm.find(".phone-box").hide().find("input").attr("disabled", true);
        currentForm.find(".email-box").hide().find("input").attr("disabled", true);
    } else {
        currentForm.find(".education-box").show().find("input").removeAttr("disabled");
        currentForm.find(".phone-box").show().find("input").removeAttr("disabled");
        currentForm.find(".email-box").show().find("input").removeAttr("disabled");
    }
}


define([
    'jquery',
    'baseUtils',
    'base',
    'msgTool',
    'plugins/bootstrap-table/bootstrap-table',
    'css!global/plugins/fileInput/fileinput.min.css',
    'plugins/fileInput/fileinput.min'
], function ($, baseUtils, base, msgTool) {
    base();


    /**
     * form表单转换成json
     */
    function getFormJson(form) {
        var data = {};
        var a = $(form).serializeArray();
        $.each(a, function () {
            if (data[this.name] !== undefined) {
                if (!data[this.name].push) {
                    data[this.name] = [data[this.name]];
                }
                data[this.name].push(this.value || '');
            } else {
                data[this.name] = this.value || '';
            }
        });
        return data;
    }


    /**
     * 证件照上传
     * @param rootName      上传css的根节点名字
     * @param cssName       上传css名字
     * @param single        是否单个，true单个，false多个
     * @param filesType     文件类型1文件，0图片
     * @param showCaption   是否显示input框，false隐藏，true显示
     * @param uploadText    按钮文件
     * @param errorCssName  错误css名字
     * @param valName       设置值的节点名字
     * @param showName      展示图的节点名字
     */
    function uploaCard(rootName, cssName, single, filesType, showCaption, uploadText, errorCssName, valName, showName) {
        //节点判断
        var valNode, showNode, errorNode;
        if (rootName !== null) {
            valNode = $(rootName).find(valName);
            showNode = $(rootName).find(showName);
            errorNode = $(rootName).find(errorCssName);
        } else {
            valNode = $(valName);
            showNode = $(showName);
            errorNode = $(errorCssName);
        }
        //上传
        return $.baseUtils.uploader({
            filesType: filesType,
            showCaption: showCaption,
            browseLabel: "选择" + uploadText,
            uploadLabel: "上传",
            rootName: rootName,
            cssName: cssName,
            errorCssName: errorCssName === null ? "#error-message" : errorCssName
        }).on("fileuploaded", function (event, data) {
            if (data.response !== null && data.response.status) {
                if (single) {
                    valNode.val(data.response.url);
                    showNode.html("<div class=\"mb15 mt15\"><div class=\"thumbnail images-box\"><a href=\"" + data.response.domain + data.response.url + "\" target=\"_blank\"><img src=\"" + data.response.domain + data.response.url + "\"></a></div></div>");
                } else {
                    showNode.append("<div class=\"col-xs-12 col-sm-4 mb15\"><div class=\"thumbnail images-box\"><input type=\"hidden\" name=\"companyImagesList\" value=\"" + data.response.url + "\"><a href=\"" + data.response.domain + data.response.url + "\" target=\"_blank\"><img src=\"" + data.response.domain + data.response.url + "\"></a></div><div class=\"caption\"><div class=\"btn btn-block btn-danger deletetCover\" onclick=\"$(this).parent().parent().remove()\"><i class=\"iconfont icon-remove\"></i>&nbsp;删除</div></div></div>");
                }
                // msgTool.success(uploadText + "上传成功！", "提示");
            } else {
                $(errorNode === null ? "#error-message" : errorNode).text(data.response.message);
            }
        });
    }


    //执行
    return {
        /**
         * 列表
         */

        index: function (currentAction) {
            var myTable = $('#companyChangedataList');
            //table当前行的响应事件
            window.operateEvents = {
                'click .handle': function (e, value, row) {
                    window.location.href = "../update/" + row.id;
                },

                'click .print': function (e, value, row) {
                    window.location.href = "../print/" + row.id;
                }
            };

            //table表格
            myTable.bootstrapTable({
                url: '/companyChange/index/api.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                // queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [
                    {
                        field: 'id',
                        title: '编号',
                        width: '10%'
                    }, {
                        field: 'companyName',
                        title: '公司信息',
                        width: '40%',
                        formatter: function (value, row, index) {
                            return '<b>' + value + '</b><br /><span class="text text-muted">' + row.companyAddress + '</span>'
                        }
                    },
                    {
                        field: 'createName',
                        title: '申请信息',
                        width: '15%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-user" aria-hidden="true"></i>&emsp;' + value + '<br /><i class="fa fa-clock-o" aria-hidden="true"></i>&emsp;' + row.createTime
                        }
                    }, {
                        field: 'updateName',
                        title: '更新信息',
                        width: '15%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-user" aria-hidden="true"></i>&emsp;' + value + '<br /><i class="fa fa-clock-o" aria-hidden="true"></i>&emsp;' + row.updateTime
                        }
                    },
                    {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        width: '20%',
                        formatter: operateFormatter,
                        events: operateEvents
                    }
                ]
            });

        },


        // index: function () {
        //     var myTable = $('#dataList');
        //     //table表格
        //     myTable.bootstrapTable({
        //         url: '/companyChange/index/api.json', // 接口 URL 地址
        //         cache: false, // 不缓存
        //         striped: true, // 隔行加亮
        //         pagination: true, // 开启分页功能
        //         sidePagination: 'server',//服务端分页
        //         sortOrder: 'desc', // 设置排序为反序 desc
        //         fixedColumns: true,//自动修复
        //         // queryParams:queryParams,//搜索附加参数
        //         smartDisplay: false, // 智能显示 pagination 和 cardview 等
        //         toolbar: ".toolBar", //顶部工具菜单
        //         toolbarAlign: "right", //顶部工具位置
        //         mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
        //         columns: [{
        //             field: 'companyName',
        //             title: '公司名称',
        //             align: 'center',
        //             width:60%
        //         }, {
        //             field: 'createName',
        //             title: '申请人',
        //             align: 'center'
        //         }, {
        //             field: 'createTime',
        //             title: '申请时间',
        //             align: 'center'
        //         }, {
        //             field: 'action',
        //             title: '操作',
        //             align: 'center',
        //             formatter: operateFormatter
        //         }
        //         ]
        //     });
        // },
        /**
         * 基础
         */
        base: function () {
            //上传执照
            uploaCard(null, "#imagesUploader", false, 0, true, "执照", null, null, "#imagesUploadShow");
            $("#baseSkip").on('click', function () {

            });

            $("#doSubmit").on('click', function () {
                $("#messageCode").text("系统维护中，请稍后重试！");
                $("#doSubmit").text('系统维护中');
                $("#doSubmit").attr('disabled', 'disabled');
                // var valid = $("#companyIndexForm").valid();
                // if (valid) {
                //     $.ajax({
                //         url: "/companyChange/save",
                //         type: 'POST',
                //         data: $("#companyIndexForm").serialize(),
                //         dataType: "JSON",
                //         beforeSend: function () {
                //             //触发ajax请求开始时执行
                //             $("#doSubmit").text('提交中...');
                //             $("#doSubmit").attr('disabled', 'disabled');
                //         },
                //         success: function (data) {
                //             if (data.success) {
                //                 window.location.href = "/companyChangeMember/shareholder/" + data.model.id;
                //             } else {
                //                 $("#messageCode").text(data.msg);
                //             }
                //         },
                //         error: function (error) {
                //             console.log(error);
                //             $("#messageCode").text("登录注册，请刷新页面后重试！");
                //         },
                //         complete: function () {
                //             $("#doSubmit").text("下一步");
                //             $("#doSubmit").removeAttr('disabled');
                //         }
                //     });
                // }
            });
        },
        /**
         * 股东
         */

        shareholder: function (changeId) {
            //证件正面照
            uploaCard("form[name='shareholderForm']", ".cardFrontUploader", true, 0, false, "正面照", ".front-error-message", "[name='cardFrontPicture']", ".cardFrontPictureShow");
            //证件反面照
            uploaCard("form[name='shareholderForm']", ".cardBackUploader", true, 0, false, "反面照", ".back-error-message", "[name='cardBackPicture']", ".cardBackPictureShow");
            //添加股东
            $("#addShareholder").on('click', function () {
                var formNode = $("body").find("form[name='shareholderForm']");
                var formId = formNode.length + 1;
                var formKey = "shareholder_" + formId;
                var investmentModeKey = "investmentMode_" + formId + "_";
                $("#moreShareholder").append("<form id=\"" + formKey + "\" class=\"form-horizontal\" name=\"shareholderForm\" method=\"post\" role=\"form\"><input class=\"form-control\" name=\"changeId\" type=\"hidden\" value=\"" + changeId + "\"><legend>第" + formId + "个股东信息：<button onclick=\"$(this).parents('form').remove()\" class=\"btn btn-danger mb5\">删除</button></legend><div class=\"form-group\"><label class=\"col-sm-2 control-label\">股东姓名：</label><div class=\"col-sm-5\"><input name=\"name\" class=\"form-control\" placeholder=\"请输入股东姓名\" type=\"text\" required aria-required=\"true\" minlength=\"2\" maxlength=\"50\"></div></div><div class=\"form-group\"><label class=\"col-sm-2 control-label\">证件类型：</label><div class=\"col-sm-5\"><select class=\"form-control\" name=\"cardType\" required aria-required=\"true\" onclick=\"memberCardTypeSwitch(event)\"><option selected value=\"\">请选择</option><option value=\"1\">身份证</option><option value=\"2\">营业执照副本</option><option value=\"3\">其他有效证件</option></select></div></div><div class=\"form-group\"><label class=\"col-sm-2 control-label\">证件号码：</label><div class=\"col-sm-5\"><input name=\"cardNumber\" class=\"form-control\" placeholder=\"请输入证件号码\" type=\"text\" required aria-required=\"true\" minlength=\"8\" maxlength=\"30\"></div></div><div class=\"form-group education-box\"><label class=\"col-sm-2 control-label\">股东学历：</label><div class=\"col-sm-5\"><select class=\"form-control\" name=\"education\" required aria-required=\"true\"><option selected value=\"\">请选择</option><option value=\"1\">初中</option><option value=\"2\">高中</option><option value=\"3\">中专</option><option value=\"4\">大专</option><option value=\"5\">本科</option><option value=\"6\">研究生</option><option value=\"7\">博士</option></select></div></div><div class=\"form-group phone-box\"><label class=\"col-sm-2 control-label\">联系电话：</label><div class=\"col-sm-5\"><input name=\"phone\" class=\"form-control\" placeholder=\"请输入电话\" type=\"text\" required aria-required=\"true\" minlength=\"8\" maxlength=\"18\"></div></div><div class=\"form-group email-box\"><label class=\"col-sm-2 control-label\">电子邮箱：</label><div class=\"col-sm-5\"><input name=\"email\" class=\"form-control\" placeholder=\"请输入电子邮箱\" type=\"text\" required aria-required=\"true\"></div></div><div class=\"form-group\"><label class=\"col-sm-2 control-label\">出资金额：</label><div class=\"col-sm-5\"><div class=\"input-group\"><input name=\"investmentAmount\" class=\"form-control\" placeholder=\"请输入出资金额（万元）\" type=\"number\" required aria-required=\"true\" min=\"1\" maxlength=\"10\"> <span class=\"input-group-addon\">万元</span></div></div></div><div class=\"form-group\"><label class=\"col-sm-2 control-label\">出资时间：</label><div class=\"col-sm-5\"><select class=\"form-control\" name=\"InvestmentTime\" required aria-required=\"true\"><option selected value=\"\">请选择</option><option value=\"1\">10年</option><option value=\"2\">11年</option><option value=\"3\">12年</option><option value=\"4\">13年</option><option value=\"5\">14年</option><option value=\"6\">15年</option><option value=\"7\">16年</option><option value=\"8\">17年</option><option value=\"9\">18年</option><option value=\"9\">19年</option><option value=\"9\">20年</option></select></div></div><div class=\"form-group\"><label class=\"col-sm-2 control-label\">出资方式：</label><div class=\"col-sm-5\"><label class=\"radio-inline\" for=\"" + investmentModeKey + "0\"><input type=\"checkbox\" value=\"1\" name=\"investmentModeList\" id=\"" + investmentModeKey + "0\" checked >货币</label><label class=\"radio-inline\" for=\"" + investmentModeKey + "1\"><input type=\"checkbox\" value=\"2\" name=\"investmentModeList\" id=\"" + investmentModeKey + "1\" >实物</label><label class=\"radio-inline\" for=\"" + investmentModeKey + "2\"><input type=\"checkbox\" value=\"3\" name=\"investmentModeKeyList\" id=\"" + investmentModeKey + "2\" >知识产权</label></div></div><div class=\"form-group\"><label class=\"col-sm-2 control-label\">证件正面照：</label><div class=\"col-sm-5\"><div class=\"input-group\"><input name=\"cardFrontPicture\" class=\"form-control mb10\" type=\"text\" readonly placeholder=\"请选择...\" required> <span class=\"input-group-btn\"><input name=\"files\" class=\"form-control cardFrontUploader\" type=\"file\"></span></div><div class=\"cardFrontPictureShow center-block row\"></div><div class=\"front-error-message\"></div></div></div><div class=\"form-group\"><label class=\"col-sm-2 control-label\">证件反面照：</label><div class=\"col-sm-5\"><div class=\"input-group\"><input name=\"cardBackPicture\" class=\"form-control mb10\" type=\"text\" readonly placeholder=\"请选择...\" required> <span class=\"input-group-btn\"><input name=\"files\" class=\"form-control cardBackUploader\" type=\"file\"></span></div><div class=\"cardBackPictureShow center-block row\"></div><div class=\"back-error-message\"></div></div></div><hr></form>");
                //证件正面照
                uploaCard("#" + formKey, ".cardFrontUploader", true, 0, false, "正面照", ".front-error-message", "[name='cardFrontPicture']", ".cardFrontPictureShow");
                //证件反面照
                uploaCard("#" + formKey, ".cardBackUploader", true, 0, false, "反面照", ".back-error-message", "[name='cardBackPicture']", ".cardBackPictureShow");
            });

            /**
             * 提交添加
             */
            $("#doSubmit").on('click', function () {

                    var dataFormStatus = false;
                    var form = $("form[name='shareholderForm']");
                    $.each(form, function () {
                        // dataFormStatus = $(this).valid();
                        dataFormStatus = $(this).validate().form();
                    });
                    if (dataFormStatus) {
                        var length = form.length;
                        //定义要传递的数组
                        var shareholderList = [];
                        for (var i = 1; i <= length; i++) {
                            var formJson = getFormJson($("#shareholder_" + i));
                            shareholderList.push(formJson);
                        }
                        $.ajax({
                            url: "/companyChangeMember/shareholder/save",
                            type: 'POST',
                            data: JSON.stringify(shareholderList),
                            dataType: "JSON",
                            contentType: 'application/json;charset=utf-8',
                            beforeSend: function () {
                                //触发ajax请求开始时执行
                                $("#doSubmit").text('提交中...');
                                $("#doSubmit").attr('disabled', 'disabled');
                            },
                            success: function (data) {
                                console.error(data);
                                console.error(changeId);
                                if (data.success) {
                                    console.error(data);
                                    console.error(changeId);
                                    window.location.href = "/companyChangeMember/legal/" + changeId;
                                } else {
                                    $("#messageCode").text(data.msg);
                                }
                            },
                            error: function (error) {
                                $("#messageCode").text("保存失败，请刷新当前页面后重试！");
                            },
                            complete: function () {
                                $("#doSubmit").text("下一步");
                                $("#doSubmit").removeAttr('disabled');
                            }
                        });
                    }
                }
            );
        },
        /**
         * 法人
         */
        member: function (uploaderFilesDomain, nextPage) {
            //股东下拉
            $.baseUtils.select({
                cssName: "#selectShareholder",
                dataName: "name",
                url: "/companyChangeMember/shareholder/list/" + $("#changeId").val()
            });

            //证件正面照
            uploaCard(null, "#cardFrontUploader", true, 0, false, "正面照", "#front-error-message", "#cardFrontPicture", "#cardFrontPictureShow");
            //证件反面照
            uploaCard(null, "#cardBackUploader", true, 0, false, "反面照", "#back-error-message", "#cardBackPicture", "#cardBackPictureShow");

            /**
             * 选中股东后，充填输入框
             */
            $('#selectShareholder').on('select2:select', function (event) {
                var data = event.params.data;
                $("#id").val(data.id);
                $("#name").val(data.name);
                $("#cardNumber").val(data.cardNumber);
                $("#phone").val(data.phone);
                $("#email").val(data.email);
                $("#cardType").val(data.cardType);
                $("#cardFrontPicture").val(data.cardFrontPicture);
                $("#cardFrontPictureShow").html("<div class=\"mb15 mt15\"><div class=\"thumbnail images-box\"><a href=\"" + uploaderFilesDomain + data.cardFrontPicture + "\" target=\"_blank\"><img src=\"" + uploaderFilesDomain + data.cardFrontPicture + "\"></a></div></div>");
                $("#cardBackPicture").val(data.cardBackPicture);
                $("#cardBackPictureShow").html("<div class=\"mb15 mt15\"><div class=\"thumbnail images-box\"><a href=\"" + uploaderFilesDomain + data.cardBackPicture + "\" target=\"_blank\"><img src=\"" + uploaderFilesDomain + data.cardBackPicture + "\"></a></div></div>");
                //执行cardType切换
                memberCardTypeSwitchExecute($("#cardType"), $(event.target).parents("form"));
            });


            /**
             * 提交添加
             */
            $("#doSubmit").on('click', function () {
                    var dataFormStatus = $("#memeberForm").valid();
                    if (dataFormStatus) {
                        $.ajax({
                            url: "save.json",
                            type: 'POST',
                            data: $("#memeberForm").serialize(),
                            dataType: "JSON",
                            beforeSend: function () {
                                //触发ajax请求开始时执行
                                $("#doSubmit").text('提交中...');
                                $("#doSubmit").attr('disabled', 'disabled');
                            },
                            success: function (data) {
                                if (data.success) {
                                    window.location.href = nextPage;
                                } else {
                                    $("#messageCode").text(data.msg);
                                }
                            },
                            error: function (error) {
                                $("#messageCode").text("保存失败，请刷新当前页面后重试！");
                            },
                            complete: function () {
                                $("#doSubmit").text("下一步");
                                $("#doSubmit").removeAttr('disabled');
                            }
                        });
                    }
                }
            );

        },
        /**
         * 申请成功
         */
        success: function () {
            console.log("申请成功.js。。。。。");
        }
        // /**
        //  * 经理
        //  */
        // manager: function () {
        //     console.log("经理.js。。。。。");
        // },
        // /**
        //  * 经理监事
        //  */
        // supervisor: function () {
        //     console.log("监事.js。。。。。");
        // },
        // /**
        //  * 经理监事财务负责人
        //  */
        // financial: function () {
        //     console.log("财务负责人.js。。。。。");
        // },
        // /**
        //  * 经理监事财务负责人联络人
        //  */
        // contact: function () {
        //     console.log("联络人.js。。。。。");
        // },
        // /**
        //  * 经理监事财务负责人联络人经办人
        //  */
        // operator: function () {
        //     console.log("经办人.js。。。。。");
        // }
    };
});
